#include <iostream>
#include <Windows.h>
#include <TlHelp32.h>
#include <string>

using namespace std;

DWORD GetKernelModPercentage(const FILETIME &ftKernel, const FILETIME &ftUser) {
	ULONGLONG qwKernel = (((ULONGLONG)ftKernel.dwHighDateTime) << 32) + ftKernel.dwLowDateTime;
	ULONGLONG qwUser = (((ULONGLONG)ftKernel.dwHighDateTime) << 32) + ftUser.dwLowDateTime;
	ULONGLONG qwTotal = qwKernel + qwUser;
	if (qwTotal == 0) return UINT_MAX;
	DWORD dwPct = (DWORD)(((ULONGLONG)100 * qwKernel) / qwTotal);
	return(dwPct);
}

void traveProcess(wchar_t *name) {
	HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
	PROCESSENTRY32 pe;
	ZeroMemory(&pe, sizeof(pe));
	pe.dwSize = sizeof(pe);
	BOOL bMore = Process32First(hSnapshot, &pe);
	while (bMore) {
		HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pe.th32ProcessID);
		if (hProcess != NULL) {
			wchar_t *t = wcsstr(pe.szExeFile, name);
			if (t != NULL) {
				FILETIME ftCreation, ftKnrnelMode, ftUserMode, ftExit;
				GetProcessTimes(hProcess, &ftCreation, &ftExit, &ftKnrnelMode, &ftUserMode);
				DWORD dwPctKernel = GetKernelModPercentage(ftKnrnelMode, ftUserMode);
				if (dwPctKernel != UINT_MAX) {
					std::wcout << "process ID" << pe.th32ProcessID
						<< "\t" << pe.szExeFile
						<< "\t" << dwPctKernel << "%" << std::endl;
					CloseHandle(hProcess);
				}
			}
		}
		bMore = Process32Next(hSnapshot, &pe);
	}
}

int main(int argc, char *argv[]) {
	wchar_t t[255];
	wprintf(L"please input the process name:");
	while (wscanf(L"%s", t)) {
		traveProcess(t);
		wprintf(L"\nplease input the process name:");
	}
}

